<template>
  <div class="content-wrapper" v-loading="loading">
    <div class="body">
      <div class="left section">
        <el-steps
          direction="vertical"
          :active="activeStep"
          space="80px"
          process-status="finish"
          finish-status="success"
        >
          <el-step
            v-for="(step, key) in steps"
            :key="key"
            :description="step.description"
            :title="step.title"
          ></el-step>
        </el-steps>
      </div>
      <div class="right section">
        <div class="panel" id="step2-content" v-if="activeStep == 0">
          <div class="form-wrapper">
            <el-divider content-position="left"><h3>基本信息</h3></el-divider>
            <el-form
              style="width:400px;"
              label-position="top"
              label-width="80px"
              :model="formData"
              ref="basicForm"
              :rules="rule1"
            >
              <el-form-item label="组名" prop="cn">
                <el-input v-model="formData.cn"></el-input>
              </el-form-item>
              <el-form-item label="组作用域" prop="scope">
                <el-radio v-model="formData.scope" label="Local"
                  >本地域</el-radio
                >
                <el-radio v-model="formData.scope" label="Global"
                  >全局</el-radio
                >
                <el-radio v-model="formData.scope" label="General"
                  >通用</el-radio
                >
              </el-form-item>
              <el-form-item label="组类型" prop="groupTypePart">
                <el-radio v-model="formData.groupTypePart" label="SecurityGroup"
                  >安全组</el-radio
                >
                <el-radio v-model="formData.groupTypePart" label="MailGroup"
                  >通讯组</el-radio
                >
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="panel" id="step4-content" v-if="activeStep == 1">
          <div class="form-wrapper">
            <el-divider content-position="left"><h3>添加人员</h3></el-divider>
            <el-form
              style="width:400px;"
              label-position="top"
              label-width="80px"
              :model="formData"
              ref="memberForm"
            >
              <el-form-item prop="cn">
                <el-button @click="pickPersonDialogVisible = true">
                  选择组成员</el-button
                >
                <el-button @click="importDialogVisible = true">
                  批量导入</el-button
                >
                <el-button
                  @click="
                    personList = personList.filter(
                      n => !personListSelected.includes(n.cn)
                    )
                  "
                >
                  删除</el-button
                >
              </el-form-item>
            </el-form>
            <el-table
              class="dense-table"
              :data="personList"
              empty-text="请选择组成员"
              @selection-change="handleSelectPersonChange"
            >
              <el-table-column type="selection" width="50" align="center" />

              <el-table-column
                label="员工编号"
                align="left"
                key="description"
                prop="description"
              >
                <template scope="scope">
                  <svg-icon
                    :icon-class="getIcon(scope.row)"
                    style="margin-right:5px"
                  />{{ scope.row.description }}
                </template>
              </el-table-column>

              <el-table-column
                label="中文姓名"
                align="left"
                key="displayName"
                prop="displayName"
              />
              <el-table-column
                label="英文名"
                align="left"
                key="name"
                prop="name"
              />

              <el-table-column
                label="职务"
                align="left"
                key="title"
                prop="title"
                :show-overflow-tooltip="true"
              />
              <el-table-column label="状态" align="center" key="enable">
                <template slot-scope="scope">
                  <el-switch
                    :value="scope.row.enable"
                    :active-value="true"
                    :inactive-value="false"
                  ></el-switch>
                </template>
              </el-table-column>

              <el-table-column
                label="邮箱"
                align="left"
                key="mail"
                prop="mail"
              />
              <el-table-column
                label="职务"
                align="left"
                key="department"
                prop="department"
              />
              <el-table-column
                label="操作"
                align="center"
                width="50px"
                fixed="right"
              >
                <template scope="scope">
                  <el-button
                    type="text"
                    @click="
                      personList = personList.filter(n => n.cn != scope.row.cn)
                    "
                    >删除</el-button
                  >
                </template></el-table-column
              >
            </el-table>
          </div>
        </div>
      </div>
    </div>
    <div class="footer">
      <div class="space"></div>
      <div class="btnSection">
        <div>
          <el-button
            v-if="prevStepEnable"
            class="btn"
            type="info"
            @click="prevStep()"
            >上一步</el-button
          >
          <el-button
            v-if="!isLastStep"
            :disabled="!nextStepEnable"
            class="btn"
            type="primary"
            @click="nextStep()"
            >下一步</el-button
          >
          <el-button
            v-if="isLastStep"
            :disabled="!nextStepEnable"
            class="btn"
            type="primary"
            @click="submitForm()"
            >提交</el-button
          >
        </div>
        <el-button class="btn" @click="cancel()">取消</el-button>
      </div>
    </div>

    <!-- 添加组成员弹窗 -->
    <el-dialog
      width="750px"
      :visible.sync="pickPersonDialogVisible"
      title="选择组成员"
      custom-class="pickPersonDialog"
    >
      <el-tabs type="border-card" style="min-height:300px;margin-bottom:10px;">
        <el-tab-pane label="按组织架构">
          <el-tree
            class="tree-line"
            :indent="0"
            :data="ouTree"
            :expand-on-click-node="false"
            ref="tree"
            node-key="id"
            lazy
            :props="treeProps"
            :load="getSubTree"
            highlight-current
            @current-change="queryPersonByOU"
        /></el-tab-pane>
        <el-tab-pane label="组合查询">
          <el-form label-width="100px" v-model="queryForm">
            <el-form-item label="账号">
              <el-input
                placeholder="账号"
                v-model="queryForm.account"
              ></el-input>
            </el-form-item>
            <el-form-item label="部门">
              <el-input
                placeholder="部门"
                v-model="queryForm.department"
              ></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input placeholder="邮箱" v-model="queryForm.mail"></el-input>
            </el-form-item>
            <div style="text-align:center">
              <el-button type="primary" @click="queryGroupMemberByCondition()"
                >查询</el-button
              >
            </div>
          </el-form></el-tab-pane
        >
      </el-tabs>

      <el-row :gutter="24" style=" height: 300px;">
        <!-- <el-transfer
          style="display: flex;justify-content: center;align-items: center;"
          v-model="personToSave"
          :data="personDataSource"
          :titles="['搜索人员', '待保存人员']"
        ></el-transfer> -->
        <el-col :span="11" style="height:100%">
          <el-card class="box-card" style="height:100%;overflow:auto;">
            <div slot="header" class="clearfix">
              <span>选择组成员</span>
            </div>
            <el-checkbox-group v-model="personDataSourceCheckList">
              <div
                v-for="person in personDataSource"
                :key="person.distinguishedName"
                class="text item"
              >
                <el-checkbox :label="person.cn">
                  <template
                    ><svg-icon
                      :icon-class="getIcon(person)"
                      style="margin-right:5px"
                    />{{ person.cn }}</template
                  >
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </el-card>
        </el-col>
        <el-col
          style="display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;"
          :span="2"
          ><el-button
            type="primary"
            circle
            size="mini"
            icon="el-icon-arrow-right"
            @click="toSave()"
          ></el-button>
          <el-button
            type="primary"
            circle
            size="mini"
            icon="el-icon-arrow-left"
            @click="toDataSource()"
          ></el-button>
        </el-col>
        <el-col :span="11" style="height:100%;">
          <el-card class="box-card" style="height:100%;overflow:auto;">
            <div slot="header" class="clearfix">
              <span>保存人员</span>
            </div>
            <el-checkbox-group v-model="personToSaveCheckList">
              <div
                v-for="person in personToSave"
                :key="person.cn"
                class="text item"
              >
                <el-checkbox :label="person.cn">
                  <template
                    ><svg-icon
                      :icon-class="getIcon(person)"
                      style="margin-right:5px"
                    />{{ person.cn }}</template
                  >
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </el-card>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetPickPerson">取 消</el-button>
        <el-button
          type="primary"
          @click="
            personList = personList.concat(
              personToSave.filter(n => !personList.find(r => n.cn == r.cn))
            );
            resetPickPerson();
          "
          >确定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      width="600px"
      :visible.sync="importDialogVisible"
      title="批量导入人员"
    >
      <el-form label-width="200px" v-model="importForm">
        <el-form-item label="导入方式" key="importType" prop="importType">
          <el-radio v-model="importForm.importType" label="upload"
            >上传EXCEL
          </el-radio>

          <el-radio v-model="importForm.importType" label="clipboard"
            >粘贴文本</el-radio
          >
        </el-form-item>
        <div
          style="padding:5px 20px;"
          v-if="importForm.importType == 'clipboard'"
        >
          <el-alert
            title="文本格式"
            type="info"
            description="用户账号 多个用户账号之间用回车换行"
            show-icon
          >
          </el-alert>

          <el-input
            type="textarea"
            :rows="10"
            placeholder="zhangsan1
zhangsan2
zhangsan3"
            v-model="importForm.clipboardText"
          >
          </el-input>
        </div>
      </el-form>

      <el-upload
        v-if="importForm.importType == 'upload'"
        style="text-align:center"
        class="upload-file"
        drag
        action="https://jsonplaceholder.typicode.com/posts/"
        multiple
        :before-upload="beforeUpload"
        :limit="1"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          只能上传xls/xlsx文件，且不超过10M
        </div>
        <div
          class="el-upload__tip"
          slot="tip"
          style="display: flex;justify-content: center;align-items: center;"
        >
          请按<el-link
            :href="`${env.VUE_APP_BASE_API}/ad/group/downloadGroupTemplate`"
            type="primary"
            >模板</el-link
          >填写数据后，上传Excel文件
        </div>
      </el-upload>

      <div style="text-align:center;margin-top:20px;">
        <el-button type="primary" @click="handleImport()">开始导入</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import groupApi from "@/api/activeDirectory/group";
import personApi from "@/api/activeDirectory/person";
import { orgMixin } from "../mixin/org";
export default {
  name: "addGroup",
  mixins: [orgMixin],
  data() {
    // wait / process / finish / error / success
    return {
      steps: [
        { title: "基本信息", status: "wait", description: "组的基本信息" },
        {
          title: "组成员",
          status: "wait",
          description: "选择组成员（组、用户），添加为组成员"
        },
        { title: "完成", status: "wait" }
      ],
      activeStep: 0,
      formNames: ["basicForm", "memberForm"],
      formData: {
        cn: "",
        scope: "Global",
        groupTypePart: "SecurityGroup",
        groupType: "",
        member: [],
        orgDN: ""
      },
      rule1: {
        cn: { required: true, message: "请输入组名", trigger: "blur" },
        scope: {
          required: true,
          message: "请选择组作用域",
          trigger: "blur"
        },
        groupTypePart: {
          required: true,
          message: "请选择组类型",
          trigger: "blur"
        },
        groupType: {
          validator: (rule, value, callback) => {
            if (value) {
              const checkArray = [
                "GlobalMailGroup",
                "LocalMailGroup",
                "GeneralMailGroup",
                "GlobalSecurityGroup",
                "LocalSecurityGroup",
                "GeneralSecurityGroup"
              ];
              if (!checkArray.includes(value)) {
                return callback(new Error("组类型不正确"));
              }
            }

            return callback();
          }
        }
      },

      loading: false,
      domain: "",

      //人员相关

      //选择人员弹窗
      pickPersonDialogVisible: false,

      personDataSource: [],
      personDataSourceCheckList: [],
      personToSave: [],
      personToSaveCheckList: [],

      //添加后的人员列表
      personList: [],
      personListSelected: [],
      // 查询参数
      personQuery: {
        pageNum: 1,
        pageSize: 10,
        displayName: undefined,
        cn: undefined
      },
      importDialogVisible: false,
      importForm: {
        importType: "upload", //导入数据方式 upload 或 clipboard

        clipboardText: ""
      },
      queryForm: { account: undefined, mail: undefined, department: undefined }
    };
  },
  created() {
    this.formData.orgDN = this.$route.params.distinguishedName;
    this.formData.groupType = this.groupType;
  },
  props: {},
  methods: {
    //#region 分部表单

    //上一步
    prevStep() {
      if (this.activeStep > 0) this.activeStep--;
    },

    //下一步
    nextStep() {
      if (this.activeStep < this.steps.length && this.validateForm()) {
        this.activeStep++;
      }
    },
    //取消
    cancel() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.go(-1);
    },

    //分部表单校验
    validateForm() {
      let res = false;
      this.$refs[this.currentForm].validate(valid => {
        res = valid;
        return valid;
      });
      return res;
    },

    //提交
    async submitForm() {
      if (!this.validateForm()) return;
      console.log(this.formData.orgDN);
      this.loading = true;
      this.formData.member = this.personList.map(n => n.distinguishedName);
      const res = await groupApi
        .addGroup(this.formData.orgDN, this.formData)
        .catch(n => {})
        .finally(() => {
          this.loading = false;
        });
      if (res.success) {
        this.activeStep = this.steps.length - 1;
        this.$message.success("添加完成");
        this.$store.dispatch("tagsView/delView", this.$route);
        this.$router.push("/activeDirectory/group");
      }
    },

    handleSelectPersonChange(selection) {
      this.personListSelected = selection.map(n => n.cn);
    },

    getIcon(row) {
      return row.objectCategory.includes("Group") ? "ad-group" : "ad-person";
    },
    //#endregion

    //#region 弹窗相关

    // OU树单击事件 搜索人员
    queryPersonByOU(node) {
      this.personQuery.cn = node.data.cn;
      this.personQuery.orgDN = node.data.distinguishedName;
      this.loading = true;
      groupApi
        .members(this.personQuery)
        .then(res => {
          this.personDataSource = res.data;
          this.personDataSourceCheckList = [];
          // this.personDataSource = res.data.data.map(n => ({
          //   key: n.distinguishedName,
          //   label: n.cn
          // }));
        })
        .catch()
        .finally(n => {
          this.loading = false;
        });
    },
    queryGroupMemberByCondition() {
      const { account, mail, department } = this.queryForm;
      if (!account && !mail && !department) {
        this.$message.warning("查询条件不能同时为空！");
        return;
      }
      this.loading = true;
      groupApi
        .searchMembers(this.queryForm)
        .then(res => {
          this.personDataSource = res.data;
          this.personDataSourceCheckList = [];
          // this.personDataSource = res.data.data.map(n => ({
          //   key: n.distinguishedName,
          //   label: n.cn
          // }));
        })
        .catch()
        .finally(n => {
          this.loading = false;
        });
    },
    beforeUpload(file) {
      this.files = file;
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      const isLt5M = file.size / 1024 / 1024 < 10;
      if (!extension && !extension2) {
        this.$message.warning("上传模板只能是 xls、xlsx格式!");
        return;
      }
      if (!isLt5M) {
        this.$message.warning("上传模板大小不能超过 10MB!");
        return;
      }
      this.fileName = file.name;
      return true; // 返回false不会自动上传
    },
    // 上传excel
    submitUpload() {
      if (!this.files) {
        this.$message.warning("请选择要上传的文件！");
        return false;
      }
      let fileFormData = new FormData();
      fileFormData.append("distinguishedName", this.formData.distinguishedName);
      //filename是键，file是值，就是要传的文件，test是要传的文件名
      fileFormData.append("files", this.files, this.fileName);

      fileFormData.append("isNew", true);

      let requestConfig = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      // 执行上传excel
      groupApi
        .importExcel(fileFormData)
        .then(res => {
          if (res.success) {
            this.$message.success("导入成功");
            this.personList = this.personList.concat(
              res.data.filter(n => !this.personList.find(r => n.cn == r.cn))
            );
            this.importDialogVisible = false;
          }
        })
        .catch(e => {
          console.log(e);
          // this.$message.error("excel上传失败，请重新上传");
        });
    },
    async handleImport() {
      const { importType } = this.importForm;
      if (importType == "upload") {
        this.submitUpload();
      } else if (importType == "clipboard") {
        if (!this.importForm.clipboardText) {
          this.$message.warning("请粘贴文本！");
          return;
        }

        const res = await groupApi.importMemberFromClipboard({
          text: this.importForm.clipboardText,
          distinguishedName: this.formData.distinguishedName,
          isNew: true
        });

        if (res.success) {
          this.$message.success(res.msg);
          this.personList = this.personList.concat(
            res.data.filter(n => !this.personList.find(r => n.cn == r.cn))
          );
          this.importDialogVisible = false;
        }
      }
    },
    //
    toSave() {
      this.personToSave = this.personToSave.concat(
        this.personDataSource.filter(
          n =>
            this.personDataSourceCheckList.includes(n.cn) &&
            !this.personToSave.find(r => r.cn == n.cn)
        )
      );
      this.personToSaveCheckList = this.personToSaveCheckList.concat(
        this.personDataSourceCheckList
      );
      this.personDataSource = this.personDataSource.filter(
        n =>
          !this.personDataSourceCheckList.includes(n.cn) &&
          !this.personToSave.find(r => r.cn == n.cn)
      );
      this.personDataSourceCheckList = [];
    },
    //
    toDataSource() {
      this.personDataSource = this.personDataSource.concat(
        this.personToSave.filter(
          n =>
            this.personToSaveCheckList.includes(n.cn) &&
            !this.personDataSource.find(r => r.cn == n.cn)
        )
      );
      this.personDataSourceCheckList = this.personDataSourceCheckList.concat(
        this.personToSaveCheckList
      );
      this.personToSave = this.personToSave.filter(
        n =>
          !this.personToSaveCheckList.includes(n.cn) &&
          !this.personDataSource.find(r => r.cn == n.cn)
      );
      this.personToSaveCheckList = [];
    },
    resetPickPerson() {
      this.pickPersonDialogVisible = false;
      this.personDataSource = [];
      this.personDataSourceCheckList = [];
      this.personToSave = [];
      this.personToSaveCheckList = [];
    },
    resetImportForm() {
      this.importForm.clipboardText = "";
    }

    //#endregion
  },
  computed: {
    prevStepEnable() {
      return this.activeStep > 0;
    },
    nextStepEnable() {
      return this.activeStep < this.steps.length;
    },
    groupType() {
      return this.formData.scope + this.formData.groupTypePart;
    },
    currentForm() {
      return this.formNames[this.activeStep];
    },
    isLastStep() {
      return this.activeStep == this.steps.length - 2;
    },
    env() {
      return process.env;
    }
  },
  watch: {
    groupType(val) {
      this.formData.groupType = val;
    },
    pickPersonDialogVisible(val) {
      if (val) {
        this.getTreeselect();
      }
    }
  }
};
</script>
<style scoped lang="scss">
.content-wrapper {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;

  .body {
    display: flex;
    overflow-y: auto;
    flex-direction: row;
    position: relative;
    width: 100%;
    height: 100%;
    .section {
      height: 100%;
    }
    .left {
      width: 33%;
      max-width: 456px;
      padding-left: 48px;
      padding-right: 48px;
      padding-top: 40px;
      border-right: 1px solid rgb(232, 232, 232);
      overflow-y: auto;
    }
    .right {
      padding: 0px 32px 48px 48px;
      display: flex;
      flex-direction: column;
      width: 100%;
      overflow-y: auto;
      position: relative;
      .panel {
        padding: 20px;
        .panel-title {
          max-width: 712px;
          padding-top: 48px;
          font-size: 28px;
          font-weight: 700;
          margin-bottom: 36px;
          color: rgb(0, 0, 0);
          .step-description {
            font-size: 14px;
            font-weight: 400;
            margin-bottom: 43px;
          }
        }
      }
    }
  }

  .footer {
    border-top: 1px solid rgb(232, 232, 232);
    display: flex;
    width: 100%;
    .space {
      width: 33%;
      max-width: 456px;
      padding-left: 48px;
      padding-right: 48px;
    }
    .btnSection {
      padding-right: 48px;
      padding-left: 48px;
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      padding-top: 17px;
      .left {
        display: flex;
        flex-wrap: nowrap;
      }
      .right {
        display: flex;
        flex-flow: row nowrap;
      }
      .btn {
        outline: transparent;
        position: relative;
        font-family: "Segoe UI", "Segoe UI Web (West European)", "Segoe UI",
          -apple-system, BlinkMacSystemFont, Roboto, "Helvetica Neue",
          sans-serif;
        -webkit-font-smoothing: antialiased;
        font-size: 14px;
        font-weight: 400;
        box-sizing: border-box;
        display: inline-block;
        text-decoration: none;
        text-align: center;
        cursor: pointer;
        padding: 0px 16px;
        border-radius: 2px;
        min-width: fit-content;
        height: 32px;

        white-space: nowrap;
        min-height: 32px;
        margin-bottom: 16px;
        margin-right: 16px;
        user-select: none;
      }
    }
  }
}
</style>
<style lang="scss">
.pickPersonDialog {
  .el-tabs__content {
    max-height: 250px;
    overflow: auto;
  }
  .el-dialog__body {
    padding: 0 20px;
  }
  .tree-line {
    .el-tree-node {
      position: relative;
      padding-left: 16px; // 缩进量
    }
    .el-tree-node__children {
      padding-left: 16px; // 缩进量
    }

    // 竖线
    .el-tree-node::before {
      content: "";
      height: 100%;
      width: 1px;
      position: absolute;
      left: -3px;
      top: -26px;
      border-width: 1px;
      border-left: 1px dashed #52627c;
    }
    // 当前层最后一个节点的竖线高度固定
    .el-tree-node:last-child::before {
      height: 38px; // 可以自己调节到合适数值
    }

    // 横线
    .el-tree-node::after {
      content: "";
      width: 24px;
      height: 20px;
      position: absolute;
      left: -3px;
      top: 12px;
      border-width: 1px;
      border-top: 1px dashed #52627c;
    }

    // 去掉最顶层的虚线，放最下面样式才不会被上面的覆盖了
    & > .el-tree-node::after {
      border-top: none;
    }
    & > .el-tree-node::before {
      border-left: none;
    }

    // 展开关闭的icon
    .el-tree-node__expand-icon {
      font-size: 16px;
      // 叶子节点（无子节点）
      &.is-leaf {
        color: transparent;
        // display: none; // 也可以去掉
      }
    }
  }
}
</style>
